package com.luhuiguo.cms.server.web.template;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;

import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

import com.luhuiguo.cms.server.util.PathUtils;

import freemarker.template.Template;

public class FreeMarkerTemplateView extends FreeMarkerView {

    private Template getTemplateInternal(String name, Locale locale) throws IOException {
        try {
            return (getEncoding() != null ? getConfiguration().getTemplate(name, locale, getEncoding())
                    : getConfiguration().getTemplate(name, locale));
        } catch (FileNotFoundException e) {
            return null;
        }
    }

    @Override
    protected Template getTemplate(String name, Locale locale) throws IOException {

        Template temp = null;
        String tempName = name;
        while (null == temp && null != tempName) {
            temp = getTemplateInternal(tempName, locale);
            tempName = PathUtils.getParentName(tempName);

        }
        if (null == temp) {
            throw new FileNotFoundException("Template " + name + " not found.");
        }
        return temp;
    }
}
